def farey_fast(n, d, N, D, limit):
    '''Fast computation of Farey sequence as a generator'''
    # n, d is the start fraction n/d (0,1) initially
    # N, D is the stop fraction N/D (1,1) initially
    pend = []
    while True:
        mediant_d = d + D
        if mediant_d <= limit:
            mediant_n = n + N
            pend.append((mediant_n, mediant_d, N, D))
            N = mediant_n
            D = mediant_d
        else:
            yield n, d
            if pend:
                n, d, N, D = pend.pop()
            else:
                yield N, D
                break

def solution():    
    nr = 0
    for (n, d) in farey_fast(1, 3, 1, 2, 10000):
        nr += 1
        
    print nr - 2 # -2 because we shouldn't count 1/3 and 1/2 themselves

from timeit import Timer
print Timer('solution()', 'from __main__ import solution').timeit(1)
